'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url admin/dls/pub/index1 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		const db = uniCloud.database();
		const $ = db.command.aggregate;
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------


		// 先设置默认值
		let role = "admin"
		let {
			todayStart,
			todayEnd
		} = vk.pubfn.getCommonTime(new Date());
		console.log("event", event.data);

		if (event.data.role) {
			role = event.data.role
		}
		if (event.data.start_today) {
			todayStart = event.data.start_today
		}
		if (event.data.end_today) {
			todayEnd = event.data.end_today
		}

		console.log("role===", role);
		console.log("todayStart===", todayStart);
		console.log("todayEnd===", todayEnd);




		if (role = 'admin') {
			//查询今日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					register_date: _.gte(todayStart).lt(todayEnd)
				}
			});




			//查询今日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 1,
					user_register_date: _.gte(todayStart).lt(todayEnd)
				}
			});


			//====查询充值订单里，今天一共有多少个新付费用户====
			// 执行聚合查询,今日充值新用户人数（注册时间是今天）。
			let newUsers_payNumber = await db.collection('a_recharge')
				.aggregate()
				.match({
					user_register_date: _.gte(todayStart).lt(todayEnd),
					user_id: db.command.exists(true),
					pay_status: 1
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.newUsers_payNumber = newUsers_payNumber.data.length ? newUsers_payNumber.data[0].user_count
				.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，今天一共有多少个付费用户====
			// 执行聚合查询,今日充值人数
			let newRows_userid = await db.collection('a_recharge')
				.aggregate()
				.match({
					_add_time: db.command.gte(todayStart).lt(todayEnd),
					user_id: db.command.exists(true),
					pay_status: 1
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.data.length ? newRows_userid.data[0].user_count.length : 0
			//====计算今日付费用户结束====


			//查询今日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				}
			});

			//查询今日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				}
			});

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = numberRePurchasers.affectedDocs;

			//复充率,在本地
			res.today_repeat_rate = 0;

			return res;
		}

		if (role = 'agent') {
			//查询今日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					invite_code: userInfo._id,
					register_date: _.gte(todayStart).lt(todayEnd)
				}
			});
			//查询今日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					invite_code: userInfo._id,
					pay_status: 1,
					user_register_date: _.gte(todayStart).lt(todayEnd)
				}
			});
			//====查询充值订单里，一共有多少个新付费用户====

			let jrczrs = await db.collection('a_recharge')
				.aggregate()
				.match({
					invite_code: userInfo._id,
					pay_status: 1, //状态为支付完成
					user_register_date: _.gte(todayStart).lt(todayEnd),
					_add_time: _.gte(todayStart).lt(todayEnd)
				})
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			res.newUsers_payNumber = jrczrs.data.length ? jrczrs.data[0].user_count.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，一共有多少个付费用户====
			//查询一共有多少个符合条件的充值订单，条件为：已支付+记录时间为今天
			let todayRechargeUsers = await vk.baseDao.select({
				dbName: "a_recharge", // 表名
				getCount: true, // 是否需要同时查询满足条件的记录总数量，默认false
				getMain: false, // 是否只返回rows数据，默认false
				pageIndex: 1, // 当前第几页
				pageSize: -1, // 每页条数
				// 只要user_id字段
				fieldJson: {
					user_id: true
				},
				whereJson: {
					invite_code: userInfo._id,
					pay_status: 1, //状态为支付完成
					_add_time: _.gte(todayStart).lt(todayEnd)
				}
			});
			//从数组中提取user_id字段形式新的数组
			let rows_userid = vk.pubfn.arrayObjectGetArray(todayRechargeUsers.rows, "user_id");
			//一个用户可能充值多次，因此需要去重
			var newRows_userid = [...new Set(rows_userid)]; //利用了Set结构不能接收重复数据的特点进行去重
			console.log("newRows.length=", newRows_userid.length);
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.length
			//====计算今日付费用户结束====


			//查询今日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					invite_code: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				}
			});

			//查询今日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					invite_code: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				}
			});

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					invite_code: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = numberRePurchasers.affectedDocs;

			//复充率,在本地
			res.today_repeat_rate = 0;
			return res;
		}


		if (role = 'middleman') {
			//查询今日新增用户数
			res.num = await vk.baseDao.count({
				dbName: "uni-id-users",
				whereJson: {
					middleman_id: userInfo._id,
					register_date: _.gte(todayStart).lt(todayEnd)
				}
			});
			//查询今日新用户充值总金额
			res.new_users_moneysum = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: userInfo._id,
					pay_status: 1,
					user_register_date: _.gte(todayStart).lt(todayEnd)
				}
			});



			//====查询充值订单里，今天一共有多少个新付费用户====
			let conditions1 = {
				middleman_id: userInfo._id,
				user_register_date: _.gte(todayStart).lt(todayEnd),
				user_id: db.command.exists(true),
				pay_status: 1
			}
			// 执行聚合查询,今日充值新用户人数（注册时间是今天）。
			let newUsers_payNumber = await db.collection('a_recharge')
				.aggregate()
				.match(conditions1)
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.newUsers_payNumber = newUsers_payNumber.data.length ? newUsers_payNumber.data[0].user_count
				.length : 0
			//====计算新付费用户结束====


			//====查询充值订单里，今天一共有多少个付费用户====
			// 查询条件
			let conditions2 = {
				middleman_id: userInfo._id,
				_add_time: db.command.gte(todayStart).lt(todayEnd),
				user_id: db.command.exists(true),
				pay_status: 1
			}
			// 执行聚合查询,今日充值人数
			let newRows_userid = await db.collection('a_recharge')
				.aggregate()
				.match(conditions2)
				.group({
					_id: null,
					user_count: $.addToSet('$user_id')
				})
				.end()
			//获取新付费用户数量
			res.Users_payNumber = newRows_userid.data.length ? newRows_userid.data[0].user_count.length : 0
			//====计算今日付费用户结束====


			//查询今日充值笔数 
			res.today_recharges_Number = await vk.baseDao.count({
				dbName: "a_recharge",
				whereJson: {
					middleman_id: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				}
			});

			//查询今日充值总金额
			res.today_Recharge_amount = await vk.baseDao.sum({
				dbName: "a_recharge",
				fieldName: "shifu_amount", // 需要求和的字段名
				whereJson: {
					middleman_id: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				}
			});

			//复充人数
			let orderCollection = db.collection('a_recharge');
			let numberRePurchasers = await orderCollection.aggregate()
				.match({
					middleman_id: userInfo._id,
					pay_status: 1,
					_add_time: _.gte(todayStart).lt(todayEnd)
				})
				.group({
					_id: '$user_id',
					count: {
						$sum: 1
					}
				})
				.match({
					count: {
						$gt: 1
					}
				})
				.count('distinctBuyerCount')
				.end()
			console.log("numberRePurchasers=", numberRePurchasers);
			res.today_repeat_user = numberRePurchasers.affectedDocs;

			//复充率,在本地
			res.today_repeat_rate = 0;

			return res;
		}



		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}